<template>
  <div class="login-container">
    <div class="content">
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
        <h2 id="h21">恒丰海泰-后台登录</h2>
        <label class="label_ls">
          <span class="span_ls">账号</span>
          <el-form-item prop="username">
            <el-input
              ref="username"
              v-model="loginForm.username"
              name="username"
              type="text"
              tabindex="1"
              autocomplete="on"
              placeholder="请输入账号"
            />
          </el-form-item>
        </label>
        <label class="label_ls">
          <span class="span_ls">密码</span>
          <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
            <el-form-item prop="password">
              <el-input
                ref="password"
                v-model="loginForm.password"
                :type="passwordType"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleLogin"
                placeholder="请输入密码"
              />
            </el-form-item>
          </el-tooltip>
        </label>
        <p class="forgot-pass"><a href="javascript:">忘记密码？</a></p>
        <el-button class="submit" id="button1" type="button" :loading="loading" @click.native.prevent="handleLogin">登 录</el-button>
        <div style="margin: 25px auto 0;text-align: center;">
          <div>
            <SocialSign :isDialog="isDialog"/>
          </div>
        </div>
      </el-form>
    </div>
    <!--  弹出层  -->
    <el-dialog title="有效时间10分钟" width="20%" :visible.sync="showDialog" @close="closeDialog">
      <div style="margin: 0 auto">
        <el-image :src="src" >
          <div slot="placeholder" class="image-slot">
            加载中<span class="dot">...</span>
          </div>
        </el-image>
      </div>
      <el-button type="primary" icon="el-icon-camera" @click="qrcode">打开摄像头</el-button>
    </el-dialog>
    <el-dialog title="正在识别" width="20%" :visible.sync="QRCode">
      <FaceLoginPage/>
    </el-dialog>
    <!--  弹出层  -->
  </div>
</template>

<script>
import SocialSign from './components/SocialSignin'
import FaceLoginPage from './components/faceLoginPage'

export default {
  name: 'Login',
  components: { SocialSign,FaceLoginPage },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 4) {
        callback(new Error('密码不能少于4位'))
      } else {
        callback()
      }
    }
    const validateUsername = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error('用户名不能为空'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        username: [{ required: true, trigger: 'blur', validator: validateUsername }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      QRCode:false,
      redirect: undefined,
      src:'',
      code: '',
      otherQuery: {},
      LunXun: {}
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  methods: {
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },

    // 普通登录
    handleLogin() {
      // 做验证，验证用户名和用户是否合法，只是前端验证
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 调用登录方法
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('登陆失败!!')
          return false
        }
      })
    },

    // 二维码验证
    isQrCode(){
      // 轮询查询二维码状态
      if (this.src !== ''){
        this.$store.dispatch('user/qrCodeCheck',this.code).then( res =>{
          //先判断二维码是否失效
          if(res.data === undefined || res.data === '' || res.data === null){
            // 关闭弹框并停止轮询
            this.closeDialog();//停止
            this.$message({
              message: '二维码已失效,请重新请求',
              type: 'warning'
            });
          }else{
            const {status,token,userId} = res.data
            //判断是否已经扫脸成功
            if(status === '1'){
              if(token != null){
                this.loading = true
                //将token存入vuex中
                this.$store.dispatch("user/setMyToken",token)
                  .then(()=>{
                    this.$router.push({ path: '/'})
                    this.loading = false
                    // 关闭弹框并停止轮询
                    this.closeDialog();//停止
                  })
                  .catch(() => {
                    _this.loading = false
                  })
              }
            }
          }
        })
      }
    },

    // 获取二维码信息
    isDialog(){
      this.showDialog=true

      // 调用获取二维码
      this.$store.dispatch('user/getQrCode').then( res =>{
        const {code,file} = res.data;
        this.code = code;
        this.src = file;
      })
      const _this = this;
      this.LunXun = setInterval(()=>{
        _this.isQrCode()
      },1000)
    },

    //关闭弹框的事件
    closeDialog(){
      this.showDialog = false
      clearInterval(this.LunXun );//停止
    },

    // 新标签打开落地页 吧code传过去
    qrcode(){
      let routeUrl = this.$router.resolve({
        path: "/faceLoginPage",
        query: {code:this.code}
      });
      window.open(routeUrl.href, '_blank');
    },

    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }

  }

}
</script>

<style lang="scss">

*, *:before, *:after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  width: 100%;
  height: 100%;
  font-family: 'Open Sans', Helvetica, Arial, sans-serif;
  background: #ededed;
}

.tip {
  font-size: 20px;
  margin: 40px auto 50px;
  text-align: center;
}
.el-dialog .el-dialog__body{
  display: flex;
  justify-content: center;
  align-items: center;
}

//.content {
//  overflow: hidden;
//  position: absolute;
//  left: 50%;
//  top: 50%;
//  width: 900px;
//  height: 550px;
//  margin: -300px 0 0 -450px;
//  background: #fff;
//}
.content {
  text-align: center; /*让div内部文字居中*/
  background-color: #fff;
  border-radius: 20px;
  width: 300px;
  height: 400px;
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  padding-top: 20px;
}
.sub-cont {
  overflow: hidden;
  position: absolute;
  left: 640px;
  top: 0;
  width: 900px;
  height: 100%;
  padding-left: 260px;
  background: #fff;
  transition: -webkit-transform 0.6s ease-in-out;
  transition: transform 0.6s ease-in-out, -webkit-transform 0.6s ease-in-out;
}

#button1 {
  display: block;
  margin: 0 auto;
  width: 260px;
  height: 36px;
  border-radius: 30px;
  color: #fff;
  font-size: 15px;
  cursor: pointer;
}

.content.s--signup .sub-cont {
  -webkit-transform: translate3d(-640px, 0, 0);
  transform: translate3d(-640px, 0, 0);
}

.img {
  overflow: hidden;
  z-index: 2;
  position: absolute;
  left: 0;
  top: 0;
  width: 260px;
  height: 100%;
  padding-top: 360px;
}

.img:before {
  content: '';
  position: absolute;
  right: 0;
  top: 0;
  width: 900px;
  height: 100%;
  background-image: url('../../../public/bg.jpg');
  background-size: cover;
  transition: -webkit-transform 0.6s ease-in-out;
  transition: transform 0.6s ease-in-out, -webkit-transform 0.6s ease-in-out;
}

.img:after {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
}

.label_ls {
  display: block;
  width: 260px;
  margin: 25px auto 0;
  text-align: center;
}

.label_ls .span_ls {
  font-size: 12px;
  color: #909399;
  text-transform: uppercase;
}

input {
  display: block;
  width: 100%;
  margin-top: 5px;
  padding-bottom: 5px;
  font-size: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.4);
  text-align: center;
}

.forgot-pass {
  margin-top: 17px;
  text-align: center;
  font-size: 12px;
  color: #cfcfcf;
  margin-bottom: 16px;
}

.submit {
  margin-left: 27.5%;
  margin-top: 40px;
  margin-bottom: 20px;
  background: #d4af7a;
  text-transform: uppercase;
}

.login-container{
  width: 100%;
  height: 100%;
  //background-image: url("../../../public/login_bg.jpg");  //背景1
  background-image: url('../../../public/bg.jpg');  //背景2
  //图片铺满
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
</style>

